// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.ListUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.LogisticsOrder;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.LogisticsOrderMapper;
import com.fowo.api.mapper.NavSellOrderDeclareMapper;
import com.fowo.api.mapper.NavSellOrderDetailMapper;
import com.fowo.api.mapper.NavSellOrderPlatformMapper;
import com.fowo.api.model.logistics.order.LogisticsOrderAgainOrderAction;
import com.fowo.api.model.logistics.order.LogisticsOrderCutAction;
import com.fowo.api.model.logistics.order.LogisticsOrderItemVo;
import com.fowo.api.model.logistics.order.LogisticsOrderSearchParamPo;
import com.fowo.api.model.logistics.order.LogisticsOrderUpdatedDeclareAction;
import com.fowo.api.model.logistics.order.LogisticsOrderVo;
import com.fowo.api.model.nav.sell.order.declare.NavSellOrderDeclareSearchParamPo;
import com.fowo.api.model.nav.sell.order.detail.NavSellOrderDetailSearchParamPo;
import com.fowo.api.model.nav.sell.order.platform.NavSellOrderPlatformSearchParamPo;
import com.fowo.api.service.LogisticsOrderService;
import com.fowo.api.service.NavSellOrderDeclareService;
import com.fowo.api.service.NavSellOrderDetailService;
import com.fowo.api.service.NavSellOrderPlatformService;
import com.fowo.api.user.model.JwtUserInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 订单管理物流下单 服务实现类
 * @author 蜂窝蜜造平台 配置人：鹿丙涛
 */
@Service
@Slf4j
@DataObjectType(LogisticsOrder.class)
@DS("ds24")
public class LogisticsOrderServiceImpl
  extends ServiceImpl<LogisticsOrderMapper, LogisticsOrder>
  implements LogisticsOrderService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("siteName", "sr.`name`");
      put("shopInfoShopName", "si.`shop_name`");
      put("deliveryLogisticsChannelLabel", "nlcv.`label`");
      put("deliveryWarehouseName", "w.`name`");
      put("deliveryCountryCountry", "sc.`country`");
      put("createUserName", "su.`name`");
    }
  };

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected LogisticsOrderService self;

  @Resource
  protected NavSellOrderPlatformService navSellOrderPlatformService;

  @Resource
  protected NavSellOrderDetailService navSellOrderDetailService;

  @Resource
  protected NavSellOrderDeclareService navSellOrderDeclareService;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected LogisticsOrderCutAction logisticsOrderCutAction;

  @Autowired(required = false)
  protected LogisticsOrderUpdatedDeclareAction logisticsOrderUpdatedDeclareAction;

  @Autowired(required = false)
  protected LogisticsOrderAgainOrderAction logisticsOrderAgainOrderAction;

  @Resource
  protected Validator validator;

  /**
   * 创建订单管理物流下单
   * @param model 订单管理物流下单
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(LogisticsOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    LogisticsOrder entity = new LogisticsOrder();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("订单管理物流下单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 订单管理物流下单
   */
  protected void updateAllChilds(LogisticsOrderVo model) throws Exception {
    if (model.getPlatform() != null) {
      navSellOrderPlatformService.saveAllByParentNavSellOrder(
        model.getId(),
        model.getPlatform()
      );
    }

    if (model.getProduct() != null) {
      navSellOrderDetailService.saveAllByParentNavSellOrder(
        model.getId(),
        model.getProduct()
      );
    }

    if (model.getDeclare() != null) {
      navSellOrderDeclareService.saveAllByParentNavSellOrder(
        model.getId(),
        model.getDeclare()
      );
    }
  }

  /**
   * 更新订单管理物流下单
   * @param model 订单管理物流下单
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(LogisticsOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    LogisticsOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("订单管理物流下单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "orderId",
      "createTime",
      "lastUpdateTime",
      "createUser",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新订单管理物流下单（带空值）
   * @param model 订单管理物流下单
   * @return 更新是否成功
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(LogisticsOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    LogisticsOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("订单管理物流下单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(
        LogisticsOrder::getLogisticsOrderStatus,
        model.getLogisticsOrderStatus()
      )
      .set(LogisticsOrder::getSite, model.getSite())
      .set(LogisticsOrder::getShopInfo, model.getShopInfo())
      .set(LogisticsOrder::getProviderName, model.getProviderName())
      .set(
        LogisticsOrder::getDeliveryLogisticsChannel,
        model.getDeliveryLogisticsChannel()
      )
      .set(LogisticsOrder::getDeliveryWaybillId, model.getDeliveryWaybillId())
      .set(LogisticsOrder::getDeliveryTrackId, model.getDeliveryTrackId())
      .set(
        LogisticsOrder::getDeliverySenderTaxNo,
        model.getDeliverySenderTaxNo()
      )
      .set(
        LogisticsOrder::getDeliveryRealCurrencyCode,
        model.getDeliveryRealCurrencyCode()
      )
      .set(
        LogisticsOrder::getDeliveryRealFreight,
        model.getDeliveryRealFreight()
      )
      .set(LogisticsOrder::getTag, model.getTag())
      .set(LogisticsOrder::getDeliveryWarehouse, model.getDeliveryWarehouse())
      .set(LogisticsOrder::getDeliveryRealWeight, model.getDeliveryRealWeight())
      .set(
        LogisticsOrder::getDeliveryRealWeightUnit,
        model.getDeliveryRealWeightUnit()
      )
      .set(
        LogisticsOrder::getDeliveryRealFeeWeight,
        model.getDeliveryRealFeeWeight()
      )
      .set(
        LogisticsOrder::getDeliveryRealFeeWeightUnit,
        model.getDeliveryRealFeeWeightUnit()
      )
      .set(LogisticsOrder::getDeliveryRealVolume, model.getDeliveryRealVolume())
      .set(
        LogisticsOrder::getDeliveryRealVolumeUnit,
        model.getDeliveryRealVolumeUnit()
      )
      .set(
        LogisticsOrder::getDeliveryRealSizeLength,
        model.getDeliveryRealSizeLength()
      )
      .set(
        LogisticsOrder::getDeliveryRealSizeWidth,
        model.getDeliveryRealSizeWidth()
      )
      .set(
        LogisticsOrder::getDeliveryRealSizeHeight,
        model.getDeliveryRealSizeHeight()
      )
      .set(
        LogisticsOrder::getDeliveryRealSizeUnit,
        model.getDeliveryRealSizeUnit()
      )
      .set(
        LogisticsOrder::getDeliveryThinkFreight,
        model.getDeliveryThinkFreight()
      )
      .set(LogisticsOrder::getDeliveryCountry, model.getDeliveryCountry())
      .set(LogisticsOrder::getDeliveryProvince, model.getDeliveryProvince())
      .set(LogisticsOrder::getDeliveryCity, model.getDeliveryCity())
      .set(LogisticsOrder::getDeliveryArea, model.getDeliveryArea())
      .set(
        LogisticsOrder::getDeliveryHouseNumber,
        model.getDeliveryHouseNumber()
      )
      .set(LogisticsOrder::getDeliveryCompany, model.getDeliveryCompany())
      .set(
        LogisticsOrder::getDeliveryAddressType,
        model.getDeliveryAddressType()
      )
      .set(LogisticsOrder::getDeliveryAddress1, model.getDeliveryAddress1())
      .set(LogisticsOrder::getDeliveryAddress2, model.getDeliveryAddress2())
      .set(LogisticsOrder::getDeliveryAddress3, model.getDeliveryAddress3())
      .set(LogisticsOrder::getDeliveryReceipt, model.getDeliveryReceipt())
      .set(LogisticsOrder::getDeliveryZipCode, model.getDeliveryZipCode())
      .set(LogisticsOrder::getDeliveryPhone, model.getDeliveryPhone())
      .set(LogisticsOrder::getRemark, model.getRemark())
      .set(LogisticsOrder::getBuyerLeaveWord, model.getBuyerLeaveWord())
      .set(LogisticsOrder::getLastUpdateTime, model.getLastUpdateTime())
      .set(LogisticsOrder::getLastUpdateUser, model.getLastUpdateUser())
      .set(LogisticsOrder::getDeliveryTime, model.getDeliveryTime())
      .set(
        LogisticsOrder::getDeliveryRecipientTaxNo,
        model.getDeliveryRecipientTaxNo()
      )
      .set(
        LogisticsOrder::getPickingDeliveryTime,
        model.getPickingDeliveryTime()
      )
      .set(LogisticsOrder::getErrorMessage, model.getErrorMessage())
      .set(LogisticsOrder::getSolution, model.getSolution())
      .eq(LogisticsOrder::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(LogisticsOrderSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 平台信息(platform) 对应的对象
    NavSellOrderPlatformSearchParamPo platformSearchParam =
      new NavSellOrderPlatformSearchParamPo();
    platformSearchParam.setDisableDataPremissions(true);
    platformSearchParam.setParentNavSellOrderInList(ids);
    NavSellOrderPlatformMapper localNavSellOrderPlatformMapper = ContextHolder
      .getApplicationContext()
      .getBean(NavSellOrderPlatformMapper.class);
    platformSearchParam.applySqlSegments();
    List<Long> platformIdList = localNavSellOrderPlatformMapper.searchIds(
      platformSearchParam
    );
    if (!platformIdList.isEmpty()) {
      NavSellOrderPlatformService localNavSellOrderPlatformService =
        ContextHolder
          .getApplicationContext()
          .getBean(NavSellOrderPlatformService.class);
      localNavSellOrderPlatformService.batchDelete(platformIdList);
    }

    // 处理子表字段 产品信息(product) 对应的对象
    NavSellOrderDetailSearchParamPo productSearchParam =
      new NavSellOrderDetailSearchParamPo();
    productSearchParam.setDisableDataPremissions(true);
    productSearchParam.setParentNavSellOrderInList(ids);
    NavSellOrderDetailMapper localNavSellOrderDetailMapper = ContextHolder
      .getApplicationContext()
      .getBean(NavSellOrderDetailMapper.class);
    productSearchParam.applySqlSegments();
    List<Long> productIdList = localNavSellOrderDetailMapper.searchIds(
      productSearchParam
    );
    if (!productIdList.isEmpty()) {
      NavSellOrderDetailService localNavSellOrderDetailService = ContextHolder
        .getApplicationContext()
        .getBean(NavSellOrderDetailService.class);
      localNavSellOrderDetailService.batchDelete(productIdList);
    }

    // 处理子表字段 报关信息(declare) 对应的对象
    NavSellOrderDeclareSearchParamPo declareSearchParam =
      new NavSellOrderDeclareSearchParamPo();
    declareSearchParam.setDisableDataPremissions(true);
    declareSearchParam.setParentNavSellOrderInList(ids);
    NavSellOrderDeclareMapper localNavSellOrderDeclareMapper = ContextHolder
      .getApplicationContext()
      .getBean(NavSellOrderDeclareMapper.class);
    declareSearchParam.applySqlSegments();
    List<Long> declareIdList = localNavSellOrderDeclareMapper.searchIds(
      declareSearchParam
    );
    if (!declareIdList.isEmpty()) {
      NavSellOrderDeclareService localNavSellOrderDeclareService = ContextHolder
        .getApplicationContext()
        .getBean(NavSellOrderDeclareService.class);
      localNavSellOrderDeclareService.batchDelete(declareIdList);
    }
  }

  /**
   * 删除订单管理物流下单
   * @param id 订单管理物流下单的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除订单管理物流下单
   * @param ids 订单管理物流下单的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 通过系统单号查询订单管理物流下单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByOrderId(String orderId) {
    return this.baseMapper.getIdByOrderId(orderId);
  }

  /**
   * 通过系统单号查询订单管理物流下单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByOrderId(List<String> list) {
    return this.baseMapper.getIdsByOrderId(list);
  }

  /**
   * 通过订单管理物流下单主键查询系统单号
   */
  @Override
  public String getOrderIdById(Long id) {
    return this.baseMapper.getOrderIdById(id);
  }

  /**
   * 通过订单管理物流下单主键查询系统单号列表
   */
  @Override
  public List<String> getOrderIdByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getOrderIdByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("orderId"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 订单管理物流下单的主键
   */
  @Override
  public LogisticsOrderVo getVoById(Long id) throws Exception {
    LogisticsOrderVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    NavSellOrderPlatformSearchParamPo platformSearchParamPo =
      new NavSellOrderPlatformSearchParamPo();
    platformSearchParamPo.setParentNavSellOrder(id);
    platformSearchParamPo.getExtendData().put("queryMode", "sub");
    platformSearchParamPo.getExtendData().put("queryParent", "LogisticsOrder");
    platformSearchParamPo.applySqlSegments();
    vo.setPlatform(navSellOrderPlatformService.search(platformSearchParamPo));

    NavSellOrderDetailSearchParamPo productSearchParamPo =
      new NavSellOrderDetailSearchParamPo();
    productSearchParamPo.setParentNavSellOrder(id);
    productSearchParamPo.getExtendData().put("queryMode", "sub");
    productSearchParamPo.getExtendData().put("queryParent", "LogisticsOrder");
    productSearchParamPo.applySqlSegments();
    vo.setProduct(navSellOrderDetailService.search(productSearchParamPo));

    NavSellOrderDeclareSearchParamPo declareSearchParamPo =
      new NavSellOrderDeclareSearchParamPo();
    declareSearchParamPo.setParentNavSellOrder(id);
    declareSearchParamPo.getExtendData().put("queryMode", "sub");
    declareSearchParamPo.getExtendData().put("queryParent", "LogisticsOrder");
    declareSearchParamPo.applySqlSegments();
    vo.setDeclare(navSellOrderDeclareService.search(declareSearchParamPo));

    return vo;
  }

  /**
   * 主列表上要附加“平台信息”子表的部分字段
   * @param items 项目列表
   * @param sort 子表排序
   */
  protected void fillPartOfPlatform(
    List<LogisticsOrderItemVo> items,
    String sort
  ) {
    NavSellOrderPlatformSearchParamPo platformSearchParamPo =
      new NavSellOrderPlatformSearchParamPo();
    platformSearchParamPo.setSort(sort);
    platformSearchParamPo.setSelectFields(
      List.of(
        "parentNavSellOrder",
        "platformOrderId",
        "platform",
        "latestShipTime"
      )
    );
    platformSearchParamPo.setParentNavSellOrderInList(
      items
        .stream()
        .map(LogisticsOrderItemVo::getId)
        .collect(Collectors.toList())
    );
    navSellOrderPlatformService
      .search(platformSearchParamPo)
      .forEach(platform -> {
        LogisticsOrderItemVo item = ListUtils.find(
          items,
          i -> Objects.equals(i.getId(), platform.getParentNavSellOrder())
        );
        if (item == null) return;
        if (item.getPlatformPlatformOrderId() == null) {
          item.setPlatformPlatformOrderId(new ArrayList<>());
        }
        item.getPlatformPlatformOrderId().add(platform.getPlatformOrderId());

        if (item.getPlatformPlatform() == null) {
          item.setPlatformPlatform(new ArrayList<>());
        }
        item.getPlatformPlatform().add(platform.getPlatform());

        if (item.getPlatformLatestShipTime() == null) {
          item.setPlatformLatestShipTime(new ArrayList<>());
        }
        item.getPlatformLatestShipTime().add(platform.getLatestShipTime());
      });
  }

  /**
   * 主列表上要附加“产品信息”子表的部分字段
   * @param items 项目列表
   * @param sort 子表排序
   */
  protected void fillPartOfProduct(
    List<LogisticsOrderItemVo> items,
    String sort
  ) {
    NavSellOrderDetailSearchParamPo productSearchParamPo =
      new NavSellOrderDetailSearchParamPo();
    productSearchParamPo.setSort(sort);
    productSearchParamPo.setSelectFields(List.of("parentNavSellOrder", "img"));
    productSearchParamPo.setParentNavSellOrderInList(
      items
        .stream()
        .map(LogisticsOrderItemVo::getId)
        .collect(Collectors.toList())
    );
    navSellOrderDetailService
      .search(productSearchParamPo)
      .forEach(product -> {
        LogisticsOrderItemVo item = ListUtils.find(
          items,
          i -> Objects.equals(i.getId(), product.getParentNavSellOrder())
        );
        if (item == null) return;
        if (item.getProductImg() == null) {
          item.setProductImg(new ArrayList<>());
        }
        item.getProductImg().add(product.getImg());
      });
  }

  /**
   * 主列表上要附加“报关信息”子表的部分字段
   * @param items 项目列表
   * @param sort 子表排序
   */
  protected void fillPartOfDeclare(
    List<LogisticsOrderItemVo> items,
    String sort
  ) {
    NavSellOrderDeclareSearchParamPo declareSearchParamPo =
      new NavSellOrderDeclareSearchParamPo();
    declareSearchParamPo.setSort(sort);
    declareSearchParamPo.setSelectFields(List.of("parentNavSellOrder", "sku"));
    declareSearchParamPo.setParentNavSellOrderInList(
      items
        .stream()
        .map(LogisticsOrderItemVo::getId)
        .collect(Collectors.toList())
    );
    navSellOrderDeclareService
      .search(declareSearchParamPo)
      .forEach(declare -> {
        LogisticsOrderItemVo item = ListUtils.find(
          items,
          i -> Objects.equals(i.getId(), declare.getParentNavSellOrder())
        );
        if (item == null) return;
        if (item.getDeclareSku() == null) {
          item.setDeclareSku(new ArrayList<>());
        }
        item.getDeclareSku().add(declare.getSku());
      });
  }

  /**
   * 分页查询订单管理物流下单
   * @param search 查询条件
   * @return 订单管理物流下单分页查询结果
   */
  @Override
  public Page<LogisticsOrderItemVo> pageSearch(
    LogisticsOrderSearchParamPo search
  ) {
    Page<LogisticsOrderItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(LogisticsOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 订单管理物流下单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'LogisticsOrderOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<LogisticsOrderItemVo>> searchOptions(
    LogisticsOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询订单管理物流下单
   * @param search 查询条件
   * @return 订单管理物流下单列表查询结果
   */
  @Override
  public List<LogisticsOrderItemVo> search(LogisticsOrderSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询订单管理物流下单最后更新时间
   * @param search 查询条件
   * @return 订单管理物流下单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(LogisticsOrderSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 截单
   */
  @Override
  public void cut(List<Long> ids) throws Exception {
    if (logisticsOrderCutAction == null) {
      throw new Exception("此操作当前不可用");
    }
    logisticsOrderCutAction.run(ids);
  }

  /**
   * 更新报关信息
   */
  @Override
  public void updatedDeclare(List<Long> ids) throws Exception {
    if (logisticsOrderUpdatedDeclareAction == null) {
      throw new Exception("此操作当前不可用");
    }
    logisticsOrderUpdatedDeclareAction.run(ids);
  }

  /**
   * 重新下单
   */
  @Override
  public void againOrder(List<Long> ids) throws Exception {
    if (logisticsOrderAgainOrderAction == null) {
      throw new Exception("此操作当前不可用");
    }
    logisticsOrderAgainOrderAction.run(ids);
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    LogisticsOrderSearchParamPo search = new LogisticsOrderSearchParamPo();
    return MapUtil
      .builder()
      .put("AllOrder", this.baseMapper.allOrderCount(search))
      .put("PlaceOrder", this.baseMapper.placeOrderCount(search))
      .put("ErrorOrder", this.baseMapper.errorOrderCount(search))
      .build();
  }

  /**
   * 全部
   */
  @Override
  public List<LogisticsOrderItemVo> allOrder(
    LogisticsOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.allOrder(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<LogisticsOrderItemVo> allOrderPage(
    LogisticsOrderSearchParamPo search
  ) {
    Page<LogisticsOrderItemVo> allOrderPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return allOrderPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return allOrderPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    allOrderPage =
      this.baseMapper.allOrderPage(
          search.toPage(this.baseMapper.allOrderCount(search)),
          search
        );
    if (
      search.getFillParts() == null ||
      search.getFillParts().contains("platform")
    ) {
      fillPartOfPlatform(
        allOrderPage.getRecords(),
        search.toChildSort("platform")
      );
    }
    if (
      search.getFillParts() == null || search.getFillParts().contains("product")
    ) {
      fillPartOfProduct(
        allOrderPage.getRecords(),
        search.toChildSort("product")
      );
    }
    if (
      search.getFillParts() == null || search.getFillParts().contains("declare")
    ) {
      fillPartOfDeclare(
        allOrderPage.getRecords(),
        search.toChildSort("declare")
      );
    }
    List<Long> recordIds = allOrderPage
      .getRecords()
      .stream()
      .map(LogisticsOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return allOrderPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return allOrderPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    allOrderPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return allOrderPage;
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date allOrderLastUpdateTime(LogisticsOrderSearchParamPo search) {
    return this.baseMapper.allOrderLastUpdateTime(search);
  }

  /**
   * 下单中
   */
  @Override
  public List<LogisticsOrderItemVo> placeOrder(
    LogisticsOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.placeOrder(search);
  }

  /**
   * 下单中分页
   */
  @Override
  public Page<LogisticsOrderItemVo> placeOrderPage(
    LogisticsOrderSearchParamPo search
  ) {
    Page<LogisticsOrderItemVo> placeOrderPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return placeOrderPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return placeOrderPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    placeOrderPage =
      this.baseMapper.placeOrderPage(
          search.toPage(this.baseMapper.placeOrderCount(search)),
          search
        );
    if (
      search.getFillParts() == null ||
      search.getFillParts().contains("platform")
    ) {
      fillPartOfPlatform(
        placeOrderPage.getRecords(),
        search.toChildSort("platform")
      );
    }
    if (
      search.getFillParts() == null || search.getFillParts().contains("product")
    ) {
      fillPartOfProduct(
        placeOrderPage.getRecords(),
        search.toChildSort("product")
      );
    }
    if (
      search.getFillParts() == null || search.getFillParts().contains("declare")
    ) {
      fillPartOfDeclare(
        placeOrderPage.getRecords(),
        search.toChildSort("declare")
      );
    }
    List<Long> recordIds = placeOrderPage
      .getRecords()
      .stream()
      .map(LogisticsOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return placeOrderPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return placeOrderPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    placeOrderPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return placeOrderPage;
  }

  /**
   * 查询下单中最后更新时间
   * @param search 查询条件
   * @return 下单中最后更新时间
   */
  @Override
  public Date placeOrderLastUpdateTime(LogisticsOrderSearchParamPo search) {
    return this.baseMapper.placeOrderLastUpdateTime(search);
  }

  /**
   * 下单异常
   */
  @Override
  public List<LogisticsOrderItemVo> errorOrder(
    LogisticsOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.errorOrder(search);
  }

  /**
   * 下单异常分页
   */
  @Override
  public Page<LogisticsOrderItemVo> errorOrderPage(
    LogisticsOrderSearchParamPo search
  ) {
    Page<LogisticsOrderItemVo> errorOrderPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return errorOrderPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return errorOrderPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    errorOrderPage =
      this.baseMapper.errorOrderPage(
          search.toPage(this.baseMapper.errorOrderCount(search)),
          search
        );
    if (
      search.getFillParts() == null ||
      search.getFillParts().contains("platform")
    ) {
      fillPartOfPlatform(
        errorOrderPage.getRecords(),
        search.toChildSort("platform")
      );
    }
    if (
      search.getFillParts() == null || search.getFillParts().contains("product")
    ) {
      fillPartOfProduct(
        errorOrderPage.getRecords(),
        search.toChildSort("product")
      );
    }
    if (
      search.getFillParts() == null || search.getFillParts().contains("declare")
    ) {
      fillPartOfDeclare(
        errorOrderPage.getRecords(),
        search.toChildSort("declare")
      );
    }
    List<Long> recordIds = errorOrderPage
      .getRecords()
      .stream()
      .map(LogisticsOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return errorOrderPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return errorOrderPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    errorOrderPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return errorOrderPage;
  }

  /**
   * 查询下单异常最后更新时间
   * @param search 查询条件
   * @return 下单异常最后更新时间
   */
  @Override
  public Date errorOrderLastUpdateTime(LogisticsOrderSearchParamPo search) {
    return this.baseMapper.errorOrderLastUpdateTime(search);
  }
}
